/*
 * Hibernate Search, full-text search for your domain model
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */
package org.hibernate.search.test.performance.task;

import static org.hibernate.search.test.performance.util.Util.log;

import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.test.performance.model.Author;
import org.hibernate.search.test.performance.model.Book;
import org.hibernate.search.test.performance.scenario.TestScenarioContext;

/**
 * @author Tomas Hradec
 */
public class InsertBookTask extends AbstractTask {

	public static final Date PUBLICATION_DATE_ZERO = new Date();

	public InsertBookTask(TestScenarioContext ctx) {
		super( ctx );
	}

	@Override
	protected void execute(FullTextSession fts) {
		long bookId = getNextBookId();
		long authorId = getNextAuthorId();

		if ( ctx.testContext.verbose ) {
			if ( bookId % 100 == 0 ) {
				log( "InsertBookTask: bookId=" + bookId );
			}
		}

		Book book = new Book();
		book.setId( bookId );
		book.setTitle( "title" + bookId );
		book.setSummary( SUMMARIES[(int) ( bookId % SUMMARIES.length )] );
		book.setRating( 0.0f );
		book.setTotalSold( 0L );
		book.setPublicationDate( DateUtils.addDays( PUBLICATION_DATE_ZERO, (int) ( bookId % 1000 ) ) );
		book.getAuthors().add( new Author( authorId, "author" + authorId ) );

		fts.merge( book );
	}

	private long getNextBookId() {
		return ctx.bookIdCounter.incrementAndGet();
	}

	private long getNextAuthorId() {
		long id = ctx.authorIdCounter.get();
		if ( id > ctx.testContext.maxAuthors ) {
			return ctx.getRandomAuthorId();
		}
		else {
			return ctx.authorIdCounter.incrementAndGet();
		}
	}

	public static final String[] SUMMARIES = new String[] {
			"Success in today's IT environment requires you to view your career as a business endeavor. In this book, you'll learn how to become an entrepreneur, driving your career in the direction of your choosing. You'll learn how to build your software development career step by step, following the same path that you would follow if you were building, marketing, and selling a product. After all, your skills themselves are a product. The choices you make about which technologies to focus on and which business domains to master have at least as much impact on your success as your technical knowledge itself--don't let those choices be accidental. We'll walk through all aspects of the decision-making process, so you can ensure that you're investing your time and energy in the right areas. You'll develop a structured plan for keeping your mind engaged and your skills fresh. You'll learn how to assess your skills in terms of where they fit on the value chain, driving you away from commodity skills and toward those that are in high demand. Through a mix of high-level, thought-provoking essays and tactical `Act on It` sections, you will come away with concrete plans you can put into action immediately. You'll also get a chance to read the perspectives of several highly successful members of our industry from a variety of career paths.",
			"Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code. But it doesn’t have to be that way. Noted software expert Robert C. Martin presents a revolutionary paradigm with Clean Code: A Handbook of Agile Software Craftsmanship . Martin has teamed up with his colleagues from Object Mentor to distill their best agile practice of cleaning code “on the fly” into a book that will instill within you the values of a software craftsman and make you a better programmer—but only if you work at it. What kind of work will you be doing? You’ll be reading code—lots of code. And you will be challenged to think about what’s right about that code, and what’s wrong with it. More importantly, you will be challenged to reassess your professional values and your commitment to your craft.",
			"Quite simply, test-driven development is meant to eliminate fear in application development. While some fear is healthy (often viewed as a conscience that tells programmers to `be careful!`), the author believes that byproducts of fear include tentative, grumpy, and uncommunicative programmers who are unable to absorb constructive criticism. When programming teams buy into TDD, they immediately see positive results. They eliminate the fear involved in their jobs, and are better equipped to tackle the difficult challenges that face them. TDD eliminates tentative traits, it teaches programmers to communicate, and it encourages team members to seek out criticism However, even the author admits that grumpiness must be worked out individually! In short, the premise behind TDD is that code should be continually tested and refactored. Kent Beck teaches programmers by example, so they can painlessly and dramatically increase the quality of their work.",
			"Testing is a key component of agile development. The widespread adoption of agile methods has brought the need for effective testing into the limelight, and agile projects have transformed the role of testers. Much of a tester’s function, however, remains largely misunderstood. What is the true role of a tester? Do agile teams actually need members with QA backgrounds? What does it really mean to be an `agile tester?` Two of the industry’s most experienced agile testing practitioners and consultants, Lisa Crispin and Janet Gregory, have teamed up to bring you the definitive answers to these questions and many others. In Agile Testing, Crispin and Gregory define agile testing and illustrate the tester’s role with examples from real agile teams. They teach you how to use the agile testing quadrants to identify what testing is needed, who should do it, and what tools might help. The book chronicles an agile software development iteration from the viewpoint of a tester and explains the seven key success factors of agile testing. Readers will come away from this book understanding",
			"Getting software released to users is often a painful, risky, and time-consuming process. This groundbreaking new book sets out the principles and technical practices that enable rapid, incremental delivery of high quality, valuable new functionality to users. Through automation of the build, deployment, and testing process, and improved collaboration between developers, testers, and operations, delivery teams can get changes released in a matter of hours— sometimes even minutes–no matter what the size of a project or the complexity of its code base.",
			"Streamline software development with Jenkins, the popular Java-based open source tool that has revolutionized the way teams think about Continuous Integration (CI). This complete guide shows you how to automate your build, integration, release, and deployment processes with Jenkins—and demonstrates how CI can save you time, money, and many headaches. Ideal for developers, software architects, and project managers, Jenkins: The Definitive Guide is both a CI tutorial and a comprehensive Jenkins reference. Through its wealth of best practices and real-world tips, you'll discover how easy it is to set up a CI service with Jenkins.",
			"Git is the version control system developed by Linus Torvalds for Linux kernel development. It took the open source world by storm since its inception in 2005, and is used by small development shops and giants like Google, Red Hat, and IBM, and of course many open source projects.",
			"Pro Puppet is an in-depth guide to installing, using, and developing the popular configuration management tool Puppet. The book is a comprehensive follow-up to the previous title Pulling Strings with Puppet. Puppet provides a way to automate everything from user management to server configuration. You'll learn how to create Puppet recipes, extend Puppet, and use Facter to gather configuration data from your servers. Puppet is a must-have tool for system administrators, and Pro Puppet will teach you how to maximize its capabilities and customize it for your environment.",
			"The Ruby Programming Language is the authoritative guide to Ruby and provides comprehensive coverage of versions 1.8 and 1.9 of the language. It was written (and illustrated!) by an all-star team:",
			"If you’re a web developer or designer ready to learn Rails, this unique book is the ideal way to start. Rather than throw you into the middle of the framework’s Model-View-Controller architecture, Learning Rails 3 works from the outside in. You’ll begin with the foundations of the Web you already know, and learn how to create something visible with Rails’ view layer. Then you’ll tackle the more difficult inner layers: the database models and controller code. All you need to get started is HTML experience. Each chapter includes exercises and review questions to test your understanding as you go.",
			"Most programming languages contain good and bad parts, but JavaScript has more than its share of the bad, having been developed and released in a hurry before it could be refined. This authoritative book scrapes away these bad features to reveal a subset of JavaScript that's more reliable, readable, and maintainable than the language as a whole-a subset you can use to create truly extensible and efficient code. Considered the JavaScript expert by many people in the development community, author Douglas Crockford identifies the abundance of good ideas that make JavaScript an outstanding object-oriented programming language-ideas such as functions, loose typing, dynamic objects, and an expressive object literal notation. Unfortunately, these good ideas are mixed in with bad and downright awful ideas, like a programming model based on global variables. When Java applets failed, JavaScript became the language of the Web by default, making its popularity almost completely independent of its qualities as a programming language. In JavaScript: The Good Parts, Crockford finally digs through the steaming pile of good intentions and blunders to give you a detailed look at all the genuinely elegant parts of JavaScript, including:",
			"Take your web development skills from browser to server with Node—and learn how to write fast, highly scalable network applications on this JavaScript-based platform. With this hands-on guide, you’ll quickly master Node’s core fundamentals, gain experience with several built-in and contributed modules, and learn the differences and parallels between client- and server-side programming. Get up to speed on Node’s event-driven, asynchronous I/O model for developing data-intensive applications that are frequently accessed but computationally simple. If you’re comfortable working with JavaScript, this book provides numerous programming and deployment examples to help you take advantage of server-side development with Node.",
			"The ASP.NET MVC 4 Framework is the latest evolution of Microsoft’s ASP.NET web platform. It provides a high-productivity programming model that promotes cleaner code architecture, test-driven development, and powerful extensibility, combined with all the benefits of ASP.NET. ASP.NET MVC 4 contains a number of significant advances over previous versions. New mobile and desktop templates (employing adaptive rendering) are included together with support for jQuery Mobile for the first time. New display modes allow your application to select views based on the browser that's making the request while Code Generation Recipes for Visual Studio help you auto-generate project-specific code for a wide variety of situtations including NuGet support. In this fourth edition, the core model-view-controller (MVC) architectural concepts are not simply explained or discussed in isolation, but are demonstrated in action. You’ll work through an extended tutorial to create a working e-commerce web application that combines ASP.NET MVC with the latest C# language features and unit-testing best practices. By gaining this invaluable, practical experience, you’ll discover MVC’s strengths and weaknesses for yourself—and put your best-learned theory into practice.",
			"This new edition of Pro C# 5.0 and the .NET 4.5 Platform has been completely revised and rewritten to reflect the latest changes to the C# language specification and new advances in the .NET Framework. You'll find new chapters covering all the important new features that make .NET 4.5 the most comprehensive release yet, including:",
			"Microsoft's Windows Presentation Foundation (WPF) provides you with a development framework for building high-quality user experiences for the Windows operating system. It blends together rich content from a wide range of sources and allows you unparalleled access to the processing power of your Windows computer. Pro WPF 4.5 in C# provides a thorough, authoritative guide to how WPF really works. Packed with no-nonsense examples and practical advice you'll learn everything you need to know in order to use WPF in a professional setting. The book begins by building a firm foundation of elementary concepts, using your existing C# skills as a frame of reference, before moving on to discuss advanced concepts and demonstrate them in a hands-on way that emphasizes the time and effort savings that can be gained.",
			"Microsoft Visual Studio 2012 significantly improves developer productivity across virtually all application lifecycle management tasks, while providing first-class support for Windows 8, Windows Phone, WindowsRT, and Windows Azure cloud development. This end-to-end deep dive will help working developers squeeze maximum productivity out of Microsoft’s powerful new toolbox. The authors combine authoritative and detailed information about Microsoft’s latest IDE, with extensive insights and best practices drawn from decades of development experience. Developers will quickly get comfortable with Visual Studio 2012’s revamped interface and discover multiple opportunities to leverage the updated .NET 4.5 platform it supports. By focusing entirely on Visual Studio 2012 Professional, the authors have gone deeper into Microsoft’s core product than ever before. You’ll find expert coverage of everything from debugging through refactoring, automation through enterprise-class development. Throughout, this book’s focus is relentlessly practical: how to apply Microsoft’s tools to build better software, faster.",
			"Pro HTML5 with Visual Studio 2012 is written to help ASP .NET developers make the leap to the inevitable and exciting world of HTML5. The growing HTML5 specifications promises to revolutionize the way web sites are developed with an impressive set of built-in client-side features.  The use of HTML5 as a preferred development language in Windows 8, along with growing support from the major browser vendors, is likely to make HTML5 the de-facto standard for all future web development. The number of HTML5-capable phones alone is estimated to top 1 billion by 2013. Many professional web developers who are firmly rooted in the Microsoft toolset such as Visual Studio, Active Server Pages, and .NET are trying to understand how HTML5 fits into their world. With this book, you’ll quickly master the new HTML elements, the improved CSS features, and advanced content including audio, video, and graphic processing. You will also learn how your enterprise applications can benefit from some brand-new technology such as local storage and web sockets. Using practical hands-on demonstrations you will learn all of the really cool features that you can start using now, within your existing ASP .NET applications. Discover the future of web development with Pro HTML5 with Visual Studio 2012",
			"jQuery is one of the most popular and powerful JavaScript libraries available today. It's widely used to create rich user experiences and to simplify website and application development. It is the tool of choice for web developers everywhere and sets the standard for simplicity, flexibility and extensibility. This book demonstrates how jQuery can be used with HTML5 to achieve excellent results. In Pro jQuery, seasoned author Adam Freeman explains how to get the most from jQuery by focusing on the features you need for your project. He starts with the nuts and bolts and shows you everything through to advanced features, going in depth to give you the knowledge you need. Getting the most from jQuery is essential to truly mastering web development.",
			"The agile, lightweight, open-source Spring Framework continues to be the de facto leading enterprise Java application development framework for today's Java programmers and developers. It works with other leading open-source, agile and lightweight Java technologies like Hibernate, Groovy, MyBatis, and more. Spring now also works with Java EE and JPA 2 as well. Pro Spring 3 updates the bestselling Pro Spring with the latest that the Spring Framework has to offer: version 3.1. At 1000 pages, this is by far the most comprehensive Spring book available, thoroughly exploring the power of Spring. With Pro Spring 3, you’ll learn Spring basics and core topics, and gain access to the authors’ insights and real–world experiences with remoting, Hibernate, and EJB. Beyond the basics, you'll learn how to leverage the Spring Framework to build various tiers or parts of an enterprise Java application like transactions, the web and presentations tiers, deployment, and much more. A full sample application allows you to apply many of the technologies and techniques covered in this book and see how they work together. After reading this definitive book, you'll be armed with the power of Spring to build complex Spring applications, top to bottom.",
			"For too long, developers have worked on disorganized application projects, where every part seemed to have its own build system, and no common repository existed for information about the state of the project. Now there's help. The long-awaited official documentation to Maven is here. Written by Maven creator Jason Van Zyl and his team at Sonatype, Maven: The Definitive Guide clearly explains how this tool can bring order to your software development projects. Maven is largely replacing Ant as the build tool of choice for large open source Java projects because, unlike Ant, Maven is also a project management tool that can run reports, generate a project website, and facilitate communication among members of a working team. To use Maven, everything you need to know is in this guide. The first part demonstrates the tool's capabilities through the development, from ideation to deployment, of several sample applications -- a simple software development project, a simple web application, a multi-module project, and a multi-module enterprise project.",
			"Soon after its launch, Ant succeeded in taking the Java world by storm, becoming the most widely used tool for building applications in Java environments. Like most popular technologies, Ant quickly went through a series of early revision cycles. With each new version, more functionality was added, and more complexity was introduced. Ant evolved from a simple-to-learn build tool into a full-fledged testing and deployment environment. Ant: The Definitive Guide has been reworked, revised and expanded upon to reflect this evolution. It documents the new ways that Ant is being applied, as well as the array of optional tasks that Ant supports. In fact, this new second edition covers everything about this extraordinary build management tool from downloading and installing, to using Ant to test code. Here are just of a few of the features you'll find detailed in this comprehensive, must-have guide:",
			"Written by members of the development team that maintains Subversion, this is the official guide and reference manual for the popular open source revision control technology. The new edition covers Subversion 1.5 with a complete introduction and guided tour of its capabilities, along with best practice recommendations. Version Control with Subversion is useful for people from a wide variety of backgrounds, from those with no previous version control experience to experienced system administrators. Subversion is the perfect tool to track individual changes when several people collaborate on documentation or, particularly, software development projects. As a more powerful and flexible successor to the CVS revision control system, Subversion makes life so much simpler, allowing each team member to work separately and then merge source code changes into a single repository that keeps a record of each separate version.",
			"The utility simply known as make is one of the most enduring features of both Unix and other operating systems. First invented in the 1970s, make still turns up to this day as the central engine in most programming projects; it even builds the Linux kernel. In the third edition of the classic Managing Projects with GNU make, readers will learn why this utility continues to hold its top position in project build software, despite many younger competitors. The premise behind make is simple: after you change source files and want to rebuild your program or other output files, make checks timestamps to see what has changed and rebuilds just what you need, without wasting time rebuilding other files. But on top of this simple principle, make layers a rich collection of options that lets you manipulate multiple directories, build different versions of programs for different platforms, and customize your builds in other ways. This edition focuses on the GNU version of make, which has deservedly become the industry standard. GNU make contains powerful extensions that are explored in this book. It is also popular because it is free software and provides a version for almost every platform, including a version for Microsoft Windows as part of the free Cygwin project. Managing Projects with GNU make, 3rd Edition provides guidelines on meeting the needs of large, modern projects. Also added are a number of interesting advanced topics such as portability, parallelism, and use with Java.",
			"O'Reilly's bestselling book on Linux's bash shell is at it again. Now that Linux is an established player both as a server and on the desktop Learning the bash Shell has been updated and refreshed to account for all the latest changes. Indeed, this third edition serves as the most valuable guide yet to the bash shell. As any good programmer knows, the first thing users of the Linux operating system come face to face with is the shell the UNIX term for a user interface to the system. In other words, it's what lets you communicate with the computer via the keyboard and display. Mastering the bash shell might sound fairly simple but it isn't. In truth, there are many complexities that need careful explanation, which is just what Learning the bash Shell provides. If you are new to shell programming, the book provides an excellent introduction, covering everything from the most basic to the most advanced features. And if you've been writing shell scripts for years, it offers a great way to find out what the new shell offers. Learning the bash Shell is also full of practical examples of shell commands and programs that will make everyday use of Linux that much easier. With this book, programmers will learn:",
			"grep Pocket Reference is the first guide devoted to grep, the powerful Unix content-location utility. This handy book is ideal for system administrators, security professionals, developers, and others who want to learn more about grep and take new approaches with it -- for everything from mail filtering and system log management to malware analysis. With grep Pocket Reference, you will",
			"There's nothing that hard-core Unix and Linux users are more fanatical about than their text editor. Editors are the subject of adoration and worship, or of scorn and ridicule, depending upon whether the topic of discussion is your editor or someone else's. vi has been the standard editor for close to 30 years. Popular on Unix and Linux, it has a growing following on Windows systems, too. Most experienced system administrators cite vi as their tool of choice. And since 1986, this book has been the guide for vi. However, Unix systems are not what they were 30 years ago, and neither is this book. While retaining all the valuable features of previous editions, the 7th edition of Learning the vi and vim Editors has been expanded to include detailed information on vim, the leading vi clone. vim is the default version of vi on most Linux systems and on Mac OS X, and is available for many other operating systems too. With this guide, you learn text editing basics and advanced tools for both editors, such as multi-window editing, how to write both interactive macros and scripts to extend the editor, and power tools for programmers -- all in the easy-to-follow style that has made this book a classic.",
			"GNU Emacs is the most popular and widespread of the Emacs family of editors. It is also the most powerful and flexible. Unlike all other text editors, GNU Emacs is a complete working environment--you can stay within Emacs all day without leaving. Learning GNU Emacs, 3rd Edition tells readers how to get started with the GNU Emacs editor. It is a thorough guide that will also `grow` with you: as you become more proficient, this book will help you learn how to use Emacs more effectively. It takes you from basic Emacs usage (simple text editing) to moderately complicated customization and programming. The third edition of Learning GNU Emacs describes Emacs 21.3 from the ground up, including new user interface features such as an icon-based toolbar and an interactive interface to Emacs customization. A new chapter details how to install and run Emacs on Mac OS X, Windows, and Linux, including tips for using Emacs effectively on those platforms. ",
			"Adopted as the undisputed Perl bible soon after the first edition appeared in 1991, Programming Perl is still the go-to guide for this highly practical language. Perl began life as a super-fueled text processing utility, but quickly evolved into a general purpose programming language that’s helped hundreds of thousands of programmers, system administrators, and enthusiasts, like you, get your job done. In this much-anticipated update to `the Camel,` three renowned Perl authors cover the language up to its current version, Perl 5.14, with a preview of features in the upcoming 5.16. In a world where Unicode is increasingly essential for text processing, Perl offers the best and least painful support of any major language, smoothly integrating Unicode everywhere—including in Perl’s most popular feature: regular expressions. Important features covered by this update include:",
			"If you've mastered Python's fundamentals, you're ready to start using it to get real work done. Programming Python will show you how, with in-depth tutorials on the language's primary application domains: system administration, GUIs, and the Web. You'll also explore how Python is used in databases, networking, front-end scripting layers, text processing, and more. This book focuses on commonly used tools and libraries to give you a comprehensive understanding of Python’s many roles in practical, real-world programming. You'll learn language syntax and programming techniques in a clear and concise manner, with lots of examples that illustrate both correct usage and common idioms. Completely updated for version 3.x, Programming Python also delves into the language as a software development tool, with many code examples scaled specifically for that purpose.",
	};

}
